package com.example.rtmppusher;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.SurfaceView;

import com.example.rtmppusher.util.CameraUtils;

public class AspectRatioSurfaceView extends SurfaceView {

    Double ratio;

    public AspectRatioSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init(context, attributeSet);
    }

    protected void init(Context context, AttributeSet attributeSet) {
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (ratio == null) {
            setMeasuredDimension(width, height);
            return;
        }
        Activity activity = (Activity) getContext();
        int rotation = CameraUtils.getDisplayRotation(activity);
        if (rotation == 0 || rotation == 180)
            setMeasuredDimension(width, (int) (width * ratio));
        else
            setMeasuredDimension(width, (int) (width / ratio));
    }

    //设置宽高比
    public void setAspectRatio(int previewWidth, int previewHeight) {
        ratio = (double) previewWidth / (double) previewHeight;
    }

    //获得Surface
    public Surface getSurface() {
        return getHolder().getSurface();
    }
}

